package com.jiahe.video.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.jiahe.video.config.AppConfig;
import com.jiahe.video.config.QiNiuConfig;
import com.jiahe.video.config.StepConfig;
import com.jiahe.video.constant.LightStatus;
import com.jiahe.video.context.AppContent;
import com.jiahe.video.model.Camera;
import com.jiahe.video.model.GroupInfo;
import com.jiahe.video.service.ApiService;
import com.jiahe.video.util.AppUtil;
import com.jiahe.video.util.WeComUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public abstract class AbsCommonService {

    @Lazy
    @Resource
    private ApiService apiService;
    @Resource
    private AppConfig appConfig;
    @Resource
    private StepConfig stepConfig;
    @Resource
    private QiNiuConfig qiNiuConfig;

    /**
     * 企业微信发送消息
     * @param messageContent 消息内容
     */
    protected void sendWeComMessage(String messageContent){
        messageContent = DateUtil.now() + "\n" + AppContent.getAppContent().getTokenInfo().getNickname() + "\n" + messageContent;
        log.info("企微消息：{}", messageContent);
        WeComUtil.sendText(appConfig.getWebHook(),messageContent);
    }

    /**
     * 上传文件到七牛
     * https://developer.qiniu.com/kodo/1239/java
     * @param localFilePath
     * @param qiniuFilePath
     * @return
     */
    protected String uploadFile2QiNiu(String localFilePath,String qiniuFilePath) {
        log.info("文件上传:{}", localFilePath);
        //构造一个带指定 Region 对象的配置类
        Region defaultRegion = Region.huadong();
        String region = qiNiuConfig.getRegion();
        if("huadong".equals(region)) {
            defaultRegion = Region.huadong();
        }else if("huabei".equals(region)) {
            defaultRegion = Region.huabei();
        }else if("huanan".equals(region)) {
            defaultRegion = Region.huanan();
        }else if("beimei".equals(region)) {
            defaultRegion = Region.beimei();
        }else if("xinjiapo".equals(region)) {
            defaultRegion = Region.xinjiapo();
        }
        Configuration cfg = Configuration.create(defaultRegion);
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //文件名
        String key = qiniuFilePath;
        Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        String upToken = auth.uploadToken(qiNiuConfig.getBucket());

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            System.out.println(response.toString());
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        return qiNiuConfig.getPrefixUrl() + "/" + key;
    }

    public synchronized void notice(Camera camera, Integer personNumber,String localFilePath) {
        log.info("通知：id:{},groupId:{},person:{}",camera.getId(),camera.getGroupId(),personNumber);
        if(StrUtil.isBlank(camera.getGroupId())){
            return;
        }
        GroupInfo groupInfo;
        Map<String, GroupInfo> groupInfoMap = AppContent.getAppContent().getGroupInfoMap();
        if (groupInfoMap.get(camera.getGroupId())==null) {
            groupInfo = new GroupInfo(camera.getGroupId());
        }else{
            groupInfo = groupInfoMap.get(camera.getGroupId());
        }
        // 判断是开还是关
        String onOrOff = personNumber > 0? LightStatus.ON : LightStatus.OFF;
        // 更新临时数据
        if( !onOrOff.equals(groupInfo.getLightStatusTemp())){
            groupInfo.setLightStatusTemp(onOrOff);
            groupInfo.setLightStatusTempLastChangeTime(System.currentTimeMillis());
        }


        long length = groupInfo.getLightStatusLastChangeTime() > 0 ? System.currentTimeMillis() - groupInfo.getLightStatusTempLastChangeTime() : 0;
        log.info("前->[{}]:\t{}\t{} <-> {}\t{}\t{}",
                groupInfo.getGroupId(),
                groupInfo.getLightStatusTemp(),
                DateUtil.format(DateUtil.date(groupInfo.getLightStatusTempLastChangeTime()), "yyyy-MM-dd HH:mm:ss"),
                groupInfo.getLightStatus(),
                DateUtil.format(DateUtil.date(groupInfo.getLightStatusLastChangeTime()), "yyyy-MM-dd HH:mm:ss"),
                length > 0 ? AppUtil.formatMilliseconds(length) : "NAN"
        );
        if (!groupInfo.getLightStatusTemp().equals(groupInfo.getLightStatus())) {
            log.info("{}，发生改变1 {}<->{}", groupInfo.getGroupId(), groupInfo.getLightStatusTemp(), groupInfo.getLightStatus());
            if (LightStatus.OFF.equals( groupInfo.getLightStatusTemp()) && length / 1000 > stepConfig.getTurnOffStep()) {
                String fileName = "temp-" + localFilePath.substring(localFilePath.lastIndexOf("/")+1, localFilePath.length());
                String qiniuFilePath = "uploads/" + DateUtil.format(new Date(), "YYYYMMdd") + "/" + camera.getId() + "/" + fileName;
                String netFilePath = uploadFile2QiNiu(localFilePath, qiniuFilePath);
                log.info("{}，发生改变2 {}->{},图片:{}", groupInfo.getGroupId(), groupInfo.getLightStatusTemp(), groupInfo.getLightStatus(),netFilePath);
                groupInfo.changeStatus();
                // 关灯
                apiService.changeLightStatus(groupInfo.getGroupId(), false,netFilePath);
            }

            if (LightStatus.ON.equals( groupInfo.getLightStatusTemp() )) {
                String fileName = "temp-" + localFilePath.substring(localFilePath.lastIndexOf("/")+1, localFilePath.length());
                String qiniuFilePath = "uploads/" + DateUtil.format(new Date(), "YYYYMMdd") + "/" + camera.getId() + "/" + fileName;
                String netFilePath = uploadFile2QiNiu(localFilePath, qiniuFilePath);
                log.info("{}，发生改变2 {}->{},图片:{}", groupInfo.getGroupId(), groupInfo.getLightStatusTemp(), groupInfo.getLightStatus(),netFilePath);
                groupInfo.changeStatus();
                // 开灯
                apiService.changeLightStatus(groupInfo.getGroupId(), true,netFilePath);
            }
        }

        groupInfoMap.put(camera.getGroupId(), groupInfo);
        AppContent.getAppContent().setGroupInfoMap(groupInfoMap);


    }

}
